package com.dorm.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dorm.common.PageResult;
import com.dorm.common.Result;
import com.dorm.entity.Room;
import com.dorm.service.RoomService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 房间控制器
 */
@RestController
@RequestMapping("/room")
public class RoomController {

    @Autowired
    private RoomService roomService;

    /**
     * 分页查询
     */
    @GetMapping("/page")
    public Result<PageResult<Room>> page(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestParam(required = false) Long buildingId,
            @RequestParam(required = false) String roomNo) {
        
        Page<Room> page = roomService.pageQuery(pageNum, pageSize, buildingId, roomNo);
        PageResult<Room> result = new PageResult<>(
                page.getRecords(),
                page.getTotal(),
                page.getCurrent(),
                page.getSize()
        );
        return Result.success(result);
    }

    /**
     * 根据ID查询
     */
    @GetMapping("/{id}")
    public Result<Room> getById(@PathVariable Long id) {
        Room room = roomService.getById(id);
        return Result.success(room);
    }

    /**
     * 新增
     */
    @PostMapping
    public Result<String> add(@RequestBody Room room) {
        // 默认剩余床位等于总床位
        if (room.getAvailableBeds() == null) {
            room.setAvailableBeds(room.getBedCount());
        }
        roomService.save(room);
        return Result.success("添加成功");
    }

    /**
     * 修改
     */
    @PutMapping
    public Result<String> update(@RequestBody Room room) {
        roomService.updateById(room);
        return Result.success("修改成功");
    }

    /**
     * 删除
     */
    @DeleteMapping("/{id}")
    public Result<String> delete(@PathVariable Long id) {
        roomService.removeById(id);
        return Result.success("删除成功");
    }

    /**
     * 查询所有
     */
    @GetMapping("/list")
    public Result<List<Room>> list(@RequestParam(required = false) Long buildingId) {
        List<Room> list;
        if (buildingId != null) {
            list = roomService.lambdaQuery()
                    .eq(Room::getBuildingId, buildingId)
                    .list();
        } else {
            list = roomService.list();
        }
        return Result.success(list);
    }
}

